using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 冰冻Buff - 使目标无法移动和攻击
/// </summary>
public class FreezeBuff : BuffBase
{
    private bool m_OriginalCanMove;
    private bool m_OriginalCanAttack;
    private float m_OriginalSpeed;
    private float m_FreezeSpeedMultiplier = 0.0f; // 冰冻时速度���

    public FreezeBuff(BuffData buffData, Entity caster, Entity target) : base(buffData, caster, target)
    {
        if (buffData is FreezeData freezeData)
        {
            m_FreezeSpeedMultiplier = freezeData.SpeedMultiplier;
        }
    }

    protected override void OnStart()
    {
        base.OnStart();
        
        // 保存原始状���
        m_OriginalCanMove = Target.MoveComponent != null;
        m_OriginalCanAttack = Target.AttackComponent != null;
        
        if (Target.MoveComponent != null)
        {
            m_OriginalSpeed = Target.MoveComponent.Speed;
            // 设置冰冻速度
            Target.MoveComponent.SetSpeed(m_OriginalSpeed * m_FreezeSpeedMultiplier);
        }
        
        // 禁用攻击
        if (Target.AttackComponent != null)
        {
            Target.AttackComponent.enabled = false;
        }
        
        // 播放冰冻特效
        if (BuffData.Effect != null)
        {
            var effect = GameObject.Instantiate(BuffData.Effect, Target.transform);
            effect.transform.localPosition = Vector3.zero;
        }
        
        // 设置动画状���
        if (Target.Animator != null)
        {
            Target.Animator.SetBool("frozen", true);
            Target.Animator.SetFloat("speedMultiplier", m_FreezeSpeedMultiplier);
        }
        
        Logger.Log($"{Target.name} 被冰冻了，无法移动和攻击");
    }

    protected override void OnTick(float dt)
    {
        base.OnTick(dt);
        // 冰冻期间不需要特殊处���
    }

    protected override void OnFinish()
    {
        base.OnFinish();
        Logger.Log($"{Target.name} 冰冻效果结束");
    }

    protected override void OnRemove()
    {
        base.OnRemove();
        
        // 恢复原始状���
        if (m_OriginalCanMove && Target.MoveComponent != null)
        {
            Target.MoveComponent.SetSpeed(m_OriginalSpeed);
        }
        
        if (m_OriginalCanAttack && Target.AttackComponent != null)
        {
            Target.AttackComponent.enabled = true;
        }
        
        // 恢复动画状���
        if (Target.Animator != null)
        {
            Target.Animator.SetBool("frozen", false);
            Target.Animator.SetFloat("speedMultiplier", 1.0f);
        }
        
        // 清理特效
        var effects = Target.GetComponentsInChildren<ParticleSystem>();
        foreach (var effect in effects)
        {
            if (effect.name.Contains("Freeze"))
            {
                GameObject.Destroy(effect.gameObject);
            }
        }
    }

    public override bool IsCanMerge()
    {
        return false; // 冰冻效果不能叠加，只能刷新持续时���
    }
}
